#-*- coding: utf-8 -*-
#! /usr/bin/python

#######################################################################################
#                                                                                     #
#    File: online_keeper.py                                                           #
#    Part of 21tb_cheater                                                         #
#    Home: http://pcbeta-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
# This code is to automatically do daily task for pcbeta bbs

# Author: elsesky

import time

import urllib
import urllib2
import socket

from browser_bogus import Browser

account_list = {"":""}
cycle = 1
delay = 3610 * 22


#do not change below this if no need
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.772.0 Safari/535.1"

login_page_init = "http://nari.21tb.com/login/login.init.do?returnUrl=http%3A%2F%2Fnari.21tb.com%2Felos%2Fhtml%2Findex.init.do&elnScreen=1920*1200elnScreen"

login_page = "http://nari.21tb.com/login/login.checkLogin.do";
login_page2 = "http://nari.21tb.com/login/login.login.do";
logout_page = "http://nari.21tb.com/login/login.logout.do";



task_page = "http://i.pcbeta.com/home.php?mod=task";
task_doing_page = "http://i.pcbeta.com/home.php?mod=task&item=doing";
bangui_leaarn_pg1 = "http://bbs.pcbeta.com/viewthread-951045-7575-1.html";
post_bangui_learn_pg = "http://bbs.pcbeta.com/forum.php?mod=post&action=reply&extra=page%3D1&replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1";
bangui_ID = "75"
task_info_detail_pre = "http://i.pcbeta.com/home.php?mod=task&do=view&id="
bangui_learn_task_detail = "http://i.pcbeta.com/home.php?mod=task&do=view&id=" + bangui_ID
bangui_learn_need = False
defaulttimeout = 3

socket.setdefaulttimeout(defaulttimeout)

class ExamNotAvailable(Exception):
    def __init__(self, time):
        self.value = time
        
    def __str__(self):
        return repr(self.value)
    
class LoginFailed(Exception):
    def __init__(self, str):
        self.value = str
        
    def __str__(self):
        return repr(self.value)

def do_bangui_learn_post(user):
    #DO POST Thread
    url = bangui_leaarn_pg1;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i= 0
    while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
    bangui_leaarn_pg1_content = content;
    vtformhash = bangui_leaarn_pg1_content.split("formhash\" value=\"")[1].split("\"")[0]
#获取当前帖子提交的fid以及tid     
    fid_tid = "&fid=" + bangui_leaarn_pg1_content.split('post&action=reply&fid=') [1].split("'")[0];
#     print fid_tid;
#     print vtformhash;exit;
#     print bangui_leaarn_pg1_content;
#init content of thread post action
    threaddata = {
                     "formhash":vtformhash,
                     "message":"每日学习新版规".decode('utf-8').encode('gbk'),
                     "posttime":str(time.time()).split(".")[0],#提取当前时间
                     "subject":"",
                     "usesig":"1"
                }
    en_logindata = urllib.urlencode(threaddata)
#init thread post url
    url = post_bangui_learn_pg + fid_tid;
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
#do thread post     
    clen = 0
    i= 0
    while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
#check post
    if content.find("回复发布成功".decode("utf-8").encode("gbk")) < 0:
        print "发帖失败".decode('utf-8').encode('gbk')
        return 1;
    else:
        print "发帖成功".decode('utf-8').encode('gbk')
#do access the task url for final accept completed work
        request = urllib2.Request(bangui_learn_task_detail)
        request.add_header("User-Agent", user.user_agent)
        clen = 0
        i= 0
        while clen < 100:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                if i > 0:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            i += 1
        return 0;
    return 1

def do_get_all_new_tasks(user):
    #get task page
    print "检查是否存在新任务".decode("utf-8").encode("gbk")  
    url = task_page;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i= 0
    while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
    task_content = content
    tasks = task_content.split("http://static.pb.pbcdn.com/static/image/task/apply.gif");
#get all task url
    tasks.pop(len(tasks) - 1);
    tsklen = len(tasks);
#     i = 0
    for tsk in tasks:
#get task url ;be careful with & code
#         tasks[i] = tsk.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&");
#         request = urllib2.Request(tasks[i])
#set flag of checking if needed to do bangui thread post
        if tsk.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&").split("apply&id=")[-1] == bangui_ID:
            bangui_learn_need = True
            print '检测到版规学习任务，随后将在版规学习帖中发帖以完成任务'.decode('utf-8').encode('gbk')
        request = urllib2.Request(tsk.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&"))
        request.add_header("User-Agent", user.user_agent)
#apply all tasks
        clen = 0
        i= 0
        while clen < 100:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                if i > 0:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            i += 1
#         print result.read();
#         i += 1
    if tsklen > 0:
        print "所有任务申请完毕".decode("utf-8").encode("gbk");
        #check bangui post bool
        if bangui_learn_need:
            do_bangui_learn_post(user);
        return 0
    else:
        print "无新任务".decode("utf-8").encode("gbk")
        return 1
#method login
def do_login(user):
    print "正在登录".decode("utf-8").encode('gbk')
#     user = browser_bogus.Browser(u, p, get_random_user_agent())
    url = login_page_init
#First access,get COOKIE and store
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
#     result = user.urlOpener.open(request)
#     content = result.read();
    clen = 0
    i = 1
    while clen < 20:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
#     content = result.read();
#init content of post action
    logindata = {
                     "corpCode":"sgepri.com",
                     "referer":login_page_init,
                     "loginName":"0",
                     "loginName":user.username,
                     "password":user.password,
                     "submit.x":"52",
                     "submit.y":"8"
                }
    en_logindata = urllib.urlencode(logindata)
#init login post url login_page1只用来确认用户是否在其它地方登录过，无视即可
    url = login_page2;
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
#do login
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
#check login
    if content.find("南瑞学堂".decode("utf-8").encode("gbk")) < 0:
        print "用户".decode('utf-8').encode('gbk') + user.username + "已成功登录".decode('utf-8').encode('gbk')
        return user;
    else:
        print "登录失败,请重试".decode('utf-8').encode('gbk')
        raise LoginFailed(user.username)
#method completed task    
def do_task_doing_check(user):
    #get task doing page
    print "检查是否存在已经完成的任务".decode("utf-8").encode("gbk")    
    url = task_doing_page;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i= 0
    while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
    task_doing_content = content;
    tasksdone = task_doing_content.split("http://static.pb.pbcdn.com/static/image/task/rewardless.gif");
    tasksdone.pop(len(tasksdone) - 1);
    tasksdonelen = len(tasksdone);
    request.add_header("User-Agent", user.user_agent)
    print '刷每个已经接受的任务,确保所有已经完成的任务能够正常显示为已经完成'.decode('utf-8').encode('gbk')
    for tskd in tasksdone:
        request = urllib2.Request(task_info_detail_pre + tskd.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&").split('id=')[1])
        request.add_header("User-Agent", user.user_agent)
        clen = 0
        i= 0
        while clen < 100:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                if i > 0:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            i += 1
#重新刷新任务页面查看已经完成的任务            
    url = task_doing_page;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i= 0
    while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
    task_doing_content = content;
    tasksdone = task_doing_content.split("http://static.pb.pbcdn.com/static/image/task/reward.gif");
#get all task url
    tasksdone.pop(len(tasksdone) - 1);
    tasksdonelen = len(tasksdone);
#     i = 0
    for tskd in tasksdone:
#get taskdone url ;be careful with & code
#         tasksdone[i] = tskd.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&");
#         print tasksdone[i]
#         continue;
#         request = urllib2.Request(tasks[i])
        request = urllib2.Request(tskd.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&"))
        request.add_header("User-Agent", user.user_agent)
#apply all have been done tasks
        clen = 0
        i= 0
        while clen < 100:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                if i > 0:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            i += 1
#         print result.read();
#         i += 1
    if tasksdonelen > 0:
        print "已完成的任务刷新完毕".decode("utf-8").encode("gbk");
    else:
        print "无需要刷新的已完成任务".decode("utf-8").encode("gbk");

#   modify user refresh url
def cheat(user):
    #url = siteurl + index_page
    url = siteurl + cat_page
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    
def time2point(user):
    url = siteurl + t2p_page
    #get current points (cards)
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    lines = result.readlines()
    points = 0
    for line in lines:
        if line.find("colspan=\"3\"") > 0:
            points = int(line.split(" ")[1].split(">")[-1])
#    print points
    #acquire points
    if points >= 100:
        url = siteurl + t2p_request_page
        request = urllib2.Request(url, t2p_request)
        request.add_header("User-Agent", user.user_agent)
        result = user.urlOpener.open(request)
        print time.strftime("%Y-%m-%d %H:%M:&S"), "%d cards Get!" % points
    
    return points
    
def logout(user):
#      url = task_page
#      request = urllib2.Request(url)
#      request.add_header("User-Agent", user.user_agent)
#      result = user.urlOpener.open(request)
#      content = result.read();
#    print content;
#      vformhash = content.split("formhash\" value=\"")[1].split("\"")[0]
#    print vformhash;
#      url = logout_page + vformhash
     url = logout_page
     request = urllib2.Request(url)
     request.add_header("User-Agent", user.user_agent)
     clen = 0
     i = 1
     while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 0:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
     print "Online Keeper Logout " + user.username
            
    
if __name__ == "__main__":
    while cycle:
        print "------------------------------------------"
        print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
        user = Browser('55109', "dengbo801018", user_agent)
        do_login(user)
        logout(user)
        if cycle > 1:
            time.sleep(delay)
        cycle = cycle - 1